package com.universest.swordholder.tools

import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONObject
import com.alibaba.fastjson.JSONArray
import java.text.SimpleDateFormat
import java.util.Locale
import java.util.Scanner

fun String.normallyToBoolean(): Boolean{
    if(this.isEmpty())return false
    return when(this.lowercase()){
        "1", "true" -> true
        "0", "false" -> false
        else -> try{this.toInt() != 0} catch (e: NumberFormatException){false}
    }
}

val CharSequence.lengthWithoutSpace: Int
    get() = this.count {
        !it.isWhitespace()
    }

fun numberToChineseForShort(number: Int): String {
    return when {
        number >= 10000 -> String.format(Locale.CHINA, "%.1f万", number.toFloat() / 10000)
        else -> number.toString()
    }
}

fun String.toJsonObject(): JSONObject?{
    return try{
        JSON.parseObject(this)
    } catch (e: Exception){
        null
    }
}

fun String.toJsonArray(): JSONArray?{
    return try{
        JSON.parseArray(this)
    } catch (e: Exception){
        null
    }
}

fun Long.toFormattedDate(pattern: String): String{
    val sdf = SimpleDateFormat(pattern, Locale.CHINA)
    return sdf.format(this)
}

fun Pair<Int, Int>.toPercentage(decimalPlaces: Int = 0): String {
    val percent = (first / second.toFloat()) * 100
    return String.format("%.${decimalPlaces}f%%", percent)
}

fun Pair<Int, Int>.toNumberProgress(): String = "$first/$second"

fun Pair<Int,Int>.toFloat():Float = first.toFloat() / second

fun String.passageFormat(): String {
    val stringBuilder = StringBuilder()
    val scanner = Scanner(this)
    while (scanner.hasNextLine()){
        val line = scanner.nextLine().trim()
        if (line.isEmpty()) continue
        stringBuilder.append("　　")
        stringBuilder.append(line)
        stringBuilder.append("\n\n")
    }
    return stringBuilder.toString()
}